package com.blacktry.utils.blog;

import com.blacktry.utils.IPUtil;
import com.blacktry.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
@Slf4j
@Configuration
public class BlogViewAspect {

    @Autowired
    private RedisUtil redisUtil;

    private static final String QUESTION_KEY = "BLOG_ID:";

    /**
     * 获取当前的ServletRequest
     * @return
     */
    protected HttpServletRequest servletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.blacktry.utils.blog.BlogView)")
    public void questionViewPointCut(){}


    /**
     * 切入处理，环绕通知
     * @param joinPoint
     * @return
     */
    @Around("questionViewPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object questionId = args[0];
        Object obj = null;
        try {
            // 获取请求的ip
            String ipAddr = IPUtil.getRemoteIp(servletRequest());
            log.info("请求Ip：{}",ipAddr);
            // 设置存入的key
            String key = QUESTION_KEY + questionId;
            // 将存入到缓存中
            Long count = this.redisUtil.add(key, ipAddr);
            if (count == 0){
                log.info("该Ip：{},访问量已经访问过了",ipAddr);
            }
            obj = joinPoint.proceed();
        }catch (Exception e){
            e.fillInStackTrace();
        }
        return obj;
    }
}